package com.joint.web.action.party;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.RoleService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.AnnualBudget;
import com.joint.core.entity.AnnualBudgetDetail;
import com.joint.core.entity.RebateActivity;


import com.joint.core.entity.RebateActivityDetail;
import com.joint.core.service.AnnualBudgetDetailService;
import com.joint.core.service.AnnualBudgetService;
import com.joint.core.service.RebateActivityDetailService;
import com.joint.core.service.RebateActivityService;

import com.joint.web.action.BaseFlowAction;
import com.opensymphony.xwork2.ActionContext;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxRebateactivityAction extends BaseFlowAction {
   
  
    @Resource
    private RebateActivityService rebateActivityService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private RebateActivityDetailService rebateActivityDetailService;
    @Resource
    private AnnualBudgetService annualBudgetService;
    @Resource
    private AnnualBudgetDetailService annualBudgetDetailService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;
    @Resource
    private TaskRecordService taskRecordService;

    
    private RebateActivity rebateActivity;
    private List<Map<String,Object>> postArrayList;

    private int numStatus;
    private Users loginUser;

    //前台传到后台的数据


    //从后台传回前台的数据
    private String activityTypeId;      //活动类型字典对象ID;
    private String departId;            //所属单位对象ID
    private String usedAmount;          //已用金额
    private String actualAmount;        //实际金额
    private String remainAmount;        //剩余金额

    private List<AnnualBudgetDetail> annualBudgetDetailList;    //
    private List<BigDecimal> usedAmountList;      //实际金额数组
    private List<BigDecimal> actualAmountList;      //实际金额数组
    private List<BigDecimal> remainAmountList;      //剩余金额

    private RebateActivityDetail rebateActivityDetail;
    private String rebateActivityDetailId;//子表对象ID



    /**
     * 活动类型
     */
    private List<Dict> activityType;
    /**
     * 所属单位
     */
    private Department department;
    /**
     * 退管会活动详情
     * @return
     */
    private List<RebateActivityDetail> rebateActivityDetailList;

    private String viewtype;
    private String annualBudgetDetailId;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "rebateactivity";
    }

    /**
     * 异步查询已用金额
     * @return
     */
    public String checkUsedAmount(){
        department=new Department();
        rebateActivityDetailList=Lists.newArrayList();
        pager = new Pager();

        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
       /* if(StringUtils.isNotEmpty(departId)){
            department=departmentService.get(departId);
            params.put("department",department);
            LogUtil.info("deName:"+department.getName());
        }*/
        AnnualBudgetDetail annualBudgetDetail1=new AnnualBudgetDetail();
        if(StringUtils.isNotEmpty(annualBudgetDetailId)){

            annualBudgetDetail1=annualBudgetDetailService.get(annualBudgetDetailId.trim());
            params.put("annualBudgetDetail",annualBudgetDetail1);
        }
        pager=rebateActivityDetailService.findByPager(pager,params);
        List<RebateActivityDetail> rebateActivityDetailList;
        if (pager.getTotalCount() > 0){
            rebateActivityDetailList = (List<RebateActivityDetail>) pager.getList();
        }else{
            rebateActivityDetailList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        List<Date> dateList=Lists.newArrayList();
        BigDecimal usedAm=new BigDecimal(0);
        for(RebateActivityDetail rebateActivityDetail:rebateActivityDetailList){
                    dateList.add(rebateActivityDetail.getCreateDate());
                    Date tempDate=Collections.max(dateList);
                        if(rebateActivityDetail.getCreateDate()==tempDate){
                            rMap = new HashMap<String,Object>();
                            rMap.put("usedAmount",rebateActivityDetail.getUsedAmount());
                            JSONObject o = JSONObject.fromObject(rMap);
                            dataRows.add(o);
                        }
        }
        data.put("dataRows",dataRows);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String listfordialog(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=rebateActivityService.findByPagerAndProcessState(pager, user, "rebateactivity", FlowEnum.ProcessState.Finished, params);
        List<RebateActivity> rebateActivityList;
        if (pager.getTotalCount() > 0){
            rebateActivityList = (List<RebateActivity>) pager.getList();
        }else{
            rebateActivityList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(RebateActivity rebateActivity:rebateActivityList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",rebateActivity.getId()!=null?rebateActivity.getId():"");
           /* rMap.put("post",rebateActivity.getPost()!=null?rebateActivity.getPost().getName():"");*/
            rMap.put("creater",rebateActivity.getCreater()!=null?rebateActivity.getCreater().getName():"");
            rMap.put("selectDate",rebateActivity.getCreateDate()!=null?rebateActivity.getCreateDate().toString():"");
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String list(){
        pager = new Pager(0);
      /*  if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        //params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=rebateActivityService.findByPagerAndLimit(false, "rebateactivity", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=rebateActivityService.findByPagerAndFinish("rebateactivity", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=rebateActivityService.findByPagerAndLimit(true, "rebateactivity", pager, params);
        }

        List<RebateActivity> rebateActivitysList;
        if (pager.getTotalCount() > 0){
            rebateActivitysList = (List<RebateActivity>) pager.getList();
        }else{
            rebateActivitysList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(RebateActivity rebateActivity:rebateActivitysList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap = new HashMap<String,Object>();
            rMap.put("id",rebateActivity.getId()!=null?rebateActivity.getId():"");
            if(rebateActivity.getCreateDate()!=null){
                String year=new SimpleDateFormat("yyyy").format(rebateActivity.getCreateDate());
                String month=new SimpleDateFormat("MM").format(rebateActivity.getCreateDate());
                rMap.put("year",year);
                rMap.put("month",month);
            }else{
                rMap.put("year","");
                rMap.put("month","");
            }
            String dictName="";
            if(rebateActivity.getActivityType()!=null){
               for (Dict dict:rebateActivity.getActivityType()){
                   dictName+=dict.getName()+",";
               }
                rMap.put("dictName",dictName);
            }else{
                rMap.put("dictName","你没有输入活动名称");
            }
            /*BigInteger bigInteger = new BigInteger();*/

           /*BigDecimal allMoney=new BigDecimal(0);
            if(rebateActivity.getRebateActivityDetailList()!=null){
                for(RebateActivityDetail rebateActivityDetail:rebateActivity.getRebateActivityDetailList()){
                     allMoney=rebateActivityDetail.getAnnualBudget().getAnnualBudgetMoney().add(allMoney);
                }
                rMap.put("allMoney",allMoney);
            }else {
                rMap.put("allMoney","");
            }*/
            BigDecimal allMoney=new BigDecimal(0);
            if(rebateActivity.getRebateActivityDetailList()!=null){
                for(RebateActivityDetail rebateActivityDetail:rebateActivity.getRebateActivityDetailList()){
                    allMoney=rebateActivityDetail.getActualAmount().add(allMoney);
                }
                rMap.put("allMoney",allMoney);
            }else {
                rMap.put("allMoney","");
            }
            rMap.put("applyDate",rebateActivity.getCreateDate()!=null?new SimpleDateFormat("yyyy-MM-dd").format(rebateActivity.getCreateDate()):"");
            rMap.put("state",rebateActivity.getProcessState().value()!=null?rebateActivity.getProcessState().value():"");




            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        activityType=Lists.newArrayList();
        department=new Department();
        rebateActivityDetailList=Lists.newArrayList();

        if(StringUtils.isNotEmpty(keyId)) {
            loginUser=usersService.getLoginInfo();
            rebateActivity = rebateActivityService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);

            //活动类型对象
            if(rebateActivity.getActivityType()!=null){
                for(Dict dict:rebateActivity.getActivityType()){
                    activityType.add(dict);
                }
            }
            //所属单位
            if(rebateActivity.getDepartment()!=null){
                department=rebateActivity.getDepartment();
            }
            //退管会活动详情对象
            if(rebateActivity.getRebateActivityDetailList()!=null){
                for(RebateActivityDetail rebateActivityDetail:rebateActivity.getRebateActivityDetailList()){
                    rebateActivityDetailList.add(rebateActivityDetail);
                }
            }
        }
        return "read";
    }

    public String input(){
        activityType=Lists.newArrayList();
        department=new Department();
        rebateActivityDetailList=Lists.newArrayList();

        if (StringUtils.isNotEmpty(keyId)){

            rebateActivity = rebateActivityService.get(keyId);
            loginUser=usersService.getLoginInfo();
            numStatus = workflowService.getNumStatus(keyId, loginUser);

            //活动类型对象
            if(rebateActivity.getActivityType()!=null){
                for(Dict dict:rebateActivity.getActivityType()){
                    activityType.add(dict);
                }
            }
            //所属单位
            if(rebateActivity.getDepartment()!=null){
                department=rebateActivity.getDepartment();
            }
            //退管会活动详情对象
            if(rebateActivity.getRebateActivityDetailList()!=null){
                for(RebateActivityDetail rebateActivityDetail:rebateActivity.getRebateActivityDetailList()){
                    rebateActivityDetailList.add(rebateActivityDetail);
                }
            }

        } else {

        }
        return "input";
    }

    private void setData(){


         activityType=Lists.newArrayList();
         department=new Department();
         annualBudgetDetailList=Lists.newArrayList();
         usedAmountList=Lists.newArrayList();
         actualAmountList=Lists.newArrayList();
         remainAmountList=Lists.newArrayList();
         loginUser=usersService.getLoginInfo();
        rebateActivityDetailList=Lists.newArrayList();
         Company company=usersService.getLoginInfo().getCompany();
        if(StringUtils.isNotEmpty(keyId)){
            rebateActivity = rebateActivityService.get(keyId);
        }else{
            rebateActivity = new RebateActivity();
            rebateActivity.setCreater(usersService.getLoginInfo());

        }

        //活动类型
        if(StringUtils.isNotEmpty(activityTypeId)){
            for(String s:activityTypeId.split(",")){
                activityType.add(dictService.get(s.trim()));
            }
        }
        //所选单位
        if(StringUtils.isNotEmpty(departId)) {
            department = departmentService.get(departId);
        }
        //年度预算
        if(StringUtils.isNotEmpty(annualBudgetDetailId)){
            for(String s:annualBudgetDetailId.split(",")){
                annualBudgetDetailList.add(annualBudgetDetailService.get(s.trim()));
            }
        }
        //已用金额
        if(StringUtils.isNotEmpty(usedAmount)){
            for(String s:usedAmount.split(",")){
                BigDecimal bd=new BigDecimal(s.trim());
                usedAmountList.add(bd);
            }
        }
        //实际金额
        if(StringUtils.isNotEmpty(actualAmount)){
            for(String s:actualAmount.split(",")){
                BigDecimal bd=new BigDecimal(s.trim());
                actualAmountList.add(bd);
            }
        }
        //剩余金额
        if(StringUtils.isNotEmpty(remainAmount)){
            for(String s:remainAmount.split(",")){
                BigDecimal bd=new BigDecimal(s.trim());
                remainAmountList.add(bd);
            }
        }


        rebateActivity.setActivityType(activityType);
        rebateActivity.setDepartment(department);
        rebateActivity.setCreater(loginUser);
        rebateActivity.setCompany(company);
        rebateActivity.setYear(new SimpleDateFormat("yyyy").format(new Date()));
        rebateActivity.setMonth(new SimpleDateFormat("MM").format(new Date()));
    }

    // 保存
    public String save(){
        setData();
        int len=annualBudgetDetailList.size();
        Company company=usersService.getLoginInfo().getCompany();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                rebateActivity=rebateActivityService.get(keyId);
                rebateActivityDetailList=rebateActivity.getRebateActivityDetailList();
                for(RebateActivityDetail rebateActivityDetail:rebateActivityDetailList){
                    rebateActivityDetailService.delete(rebateActivityDetail);
                }
                rebateActivity.setRebateActivityDetailList(null);
                List<RebateActivityDetail> rebateActivityDetailList1=Lists.newArrayList();
                for(int i=0;i<len;i++){
                    RebateActivityDetail rebateActivityDetail=new RebateActivityDetail();
                    rebateActivityDetail.setAnnualBudgetDetail(annualBudgetDetailList.get(i));
                    rebateActivityDetail.setUsedAmount(usedAmountList.get(i));
                    rebateActivityDetail.setActualAmount(actualAmountList.get(i));
                    rebateActivityDetail.setRemainAmount(remainAmountList.get(i));
                    rebateActivityDetail.setRebateActivity(rebateActivity);
                    rebateActivityDetail.setCompany(company);
                    rebateActivityDetail.setState(BaseEnum.StateEnum.Enable);
                    rebateActivityDetailService.save(rebateActivityDetail);
                    rebateActivityDetailList1.add(rebateActivityDetail);
                }
                rebateActivity.setRebateActivityDetailList(rebateActivityDetailList1);
                rebateActivityService.update(rebateActivity);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                String id=rebateActivityService.save(rebateActivity, "rebateactivity", various);
                rebateActivity=rebateActivityService.get(id);
                for(int i=0;i<len;i++){
                    RebateActivityDetail rebateActivityDetail=new RebateActivityDetail();
                    rebateActivityDetail.setAnnualBudgetDetail(annualBudgetDetailList.get(i));
                    rebateActivityDetail.setUsedAmount(usedAmountList.get(i));
                    rebateActivityDetail.setActualAmount(actualAmountList.get(i));
                    rebateActivityDetail.setRemainAmount(remainAmountList.get(i));
                    rebateActivityDetail.setRebateActivity(rebateActivity);
                    rebateActivityDetail.setCompany(company);
                    rebateActivityDetail.setState(BaseEnum.StateEnum.Enable);
                    rebateActivityDetailService.save(rebateActivityDetail);
                    rebateActivityDetailList.add(rebateActivityDetail);
                }
                rebateActivity.setRebateActivityDetailList(rebateActivityDetailList);
                rebateActivityService.update(rebateActivity);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        int len=annualBudgetDetailList.size();
        Company company=usersService.getLoginInfo().getCompany();
        if(StringUtils.isNotEmpty(keyId)){
            rebateActivity=rebateActivityService.get(keyId);
            rebateActivityDetailList=rebateActivity.getRebateActivityDetailList();
            for(RebateActivityDetail rebateActivityDetail:rebateActivityDetailList){
                rebateActivityDetailService.delete(rebateActivityDetail);
            }
            rebateActivity.setRebateActivityDetailList(null);
            List<RebateActivityDetail> rebateActivityDetailList1=Lists.newArrayList();
            for(int i=0;i<len;i++){
                RebateActivityDetail rebateActivityDetail=new RebateActivityDetail();
                rebateActivityDetail.setAnnualBudgetDetail(annualBudgetDetailList.get(i));
                rebateActivityDetail.setUsedAmount(usedAmountList.get(i));
                rebateActivityDetail.setActualAmount(actualAmountList.get(i));
                rebateActivityDetail.setRemainAmount(remainAmountList.get(i));
                rebateActivityDetail.setRebateActivity(rebateActivity);
                rebateActivityDetail.setCompany(company);
                rebateActivityDetail.setState(BaseEnum.StateEnum.Enable);
                rebateActivityDetailService.save(rebateActivityDetail);
                rebateActivityDetailList1.add(rebateActivityDetail);
            }
            rebateActivity.setRebateActivityDetailList(rebateActivityDetailList1);
            rebateActivityService.update(rebateActivity);

        }else{
            rebateActivityService.save(rebateActivity);
            for(int i=0;i<len;i++){
                RebateActivityDetail rebateActivityDetail=new RebateActivityDetail();
                rebateActivityDetail.setAnnualBudgetDetail(annualBudgetDetailList.get(i));
                rebateActivityDetail.setUsedAmount(usedAmountList.get(i));
                rebateActivityDetail.setActualAmount(actualAmountList.get(i));
                rebateActivityDetail.setRemainAmount(remainAmountList.get(i));
                rebateActivityDetail.setRebateActivity(rebateActivity);
                rebateActivityDetail.setCompany(company);
                rebateActivityDetail.setState(BaseEnum.StateEnum.Enable);
                rebateActivityDetailService.save(rebateActivityDetail);
                rebateActivityDetailList.add(rebateActivityDetail);
            }
            rebateActivity.setRebateActivityDetailList(rebateActivityDetailList);
            rebateActivityService.update(rebateActivity);
        }


        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        Set<Duty> dutySet= null;
        ArrayList<Department> departmentArrayList=null;
        dutySet=usersService.getLoginInfo().getDutySet();

        /*loop1:for(Duty duty:dutySet){
            Post post = duty.getPost();//根据当前登录用户的职责，得到当前登陆用户的岗位
            if(StringUtils.equals(post.getName(),"退管会专员")  == false){
                continue;//进入当前登录人的下一个职权
            }
            Department dept = duty.getDepartment().getParent();//根据当前登陆人的职责，得到当前人的部门的上级部门
            if (dept == null) {//上级部门为空的话，进入当前人的下一个职责
                continue;
            }
            Set<Power> powers = dept.getPowerSet();//获取当前登陆人的职责，得到部门的部门的职权集合
            loop2:for(Power power:powers){//遍历姥姥级部门下的所有职权
                //   LogUtil.info("power:"+power.getId());
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记") == true) {
                    List<Users> usersList=dutyService.getPersons(dept, post1);//更具岗位对象获取该部门下的指定岗位下的 所有人
                    for(Users users1:usersList){
                        LogUtil.info("userName:"+users1.getName());
                        list.add(users1.getId());
                    }
                    break loop1;
                }
            }
        }
        var2.put("approvers",list);
*/
        if(StringUtils.isNotEmpty(departId)){
            department = departmentService.get(departId);
            Set<Power> powers = department.getPowerSet();
            for(Power power:powers){
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记")==true){
                    List<Users> usersList=dutyService.getPersons(department, post1);
                    for(Users users1:usersList){
                        list.add(users1.getId());
                    }
                }
            }
            var2.put("approvers",list);
        }
        if(StringUtils.isEmpty(comment)){
            comment="";
        }

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                rebateActivityService.approve(rebateActivity, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                rebateActivityService.commit(rebateActivity, "rebateactivity", var1, var2, curDutyId);/*返回文档的iD*/
                /*LogUtil.info("KeyId_2 = "+keyId);
                RebateActivity entity = rebateActivityService.get(keyId);*//*文档id*//*
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                rebateActivityService.save(entity);*/


            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        rebateActivity = rebateActivityService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        //var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {

                rebateActivityService.approve(rebateActivity, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
                Task overtask=workflowService.getCurrentTask(keyId);
                if(overtask==null){
                    RebateActivity entity=rebateActivityService.get(keyId);
                    entity.setProcessState(FlowEnum.ProcessState.Finished);
                    rebateActivityService.update(entity);

                    List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
                    for(TaskRecord taskRecord:taskRecords){
                        taskRecord.setType(2);
                        taskRecordService.update(taskRecord);
                    }
                }else{
                    if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){
                        runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                    }
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }

        rebateActivity=new RebateActivity();
        rebateActivity=rebateActivityService.get(keyId);
        List<RebateActivityDetail> rebateActivityDetailList=rebateActivity.getRebateActivityDetailList();
        for(RebateActivityDetail rebateActivityDetail:rebateActivityDetailList){
            BigDecimal actualAmount=rebateActivityDetail.getActualAmount();//实际金额
            BigDecimal userAmount=rebateActivityDetail.getUsedAmount();//已使用金额
            //BigDecimal remainAmount=rebateActivityDetail.getRemainAmount();//剩余金额
            Double budgetMoney=rebateActivityDetail.getAnnualBudgetDetail().getBudgetMoney();
            BigDecimal decimal=new BigDecimal(budgetMoney);// 预算金额

            rebateActivityDetail.setUsedAmount(userAmount.add(actualAmount));
            BigDecimal userAmount1=rebateActivityDetail.getUsedAmount();
            rebateActivityDetail.setRemainAmount(decimal.subtract(userAmount1));
            rebateActivityDetailService.update(rebateActivityDetail);

        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        rebateActivity = rebateActivityService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        //  var2.put("curDutyId", curDutyId);
        try {
            rebateActivityService.approve(rebateActivity, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        rebateActivity = rebateActivityService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            rebateActivityService.approve(rebateActivity, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            rebateActivity = rebateActivityService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("rebateactivity");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            rebateActivityService.reject(rebateActivity, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            rebateActivity = rebateActivityService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("rebateactivity");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            rebateActivityService.deny(rebateActivity, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public RebateActivity getRebateActivity() {
        return rebateActivity;
    }

    public void setRebateActivity(RebateActivity rebateActivity) {
        this.rebateActivity = rebateActivity;
    }
    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }


    public String getViewtype() {


        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public List<Map<String, Object>> getPostArrayList() {
        return postArrayList;
    }

    public void setPostArrayList(List<Map<String, Object>> postArrayList) {
        this.postArrayList = postArrayList;
    }



    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public List<Dict> getActivityType() {
        return activityType;
    }

    public void setActivityType(List<Dict> activityType) {
        this.activityType = activityType;
    }

    public String getActivityTypeId() {
        return activityTypeId;
    }

    public void setActivityTypeId(String activityTypeId) {
        this.activityTypeId = activityTypeId;
    }



    public String getActualAmount() {
        return actualAmount;
    }

    public void setActualAmount(String actualAmount) {
        this.actualAmount = actualAmount;
    }

    public String getRemainAmount() {
        return remainAmount;
    }

    public void setRemainAmount(String remainAmount) {
        this.remainAmount = remainAmount;
    }





    public List<BigDecimal> getActualAmountList() {
        return actualAmountList;
    }

    public void setActualAmountList(List<BigDecimal> actualAmountList) {
        this.actualAmountList = actualAmountList;
    }

    public List<BigDecimal> getRemainAmountList() {
        return remainAmountList;
    }

    public void setRemainAmountList(List<BigDecimal> remainAmountList) {
        this.remainAmountList = remainAmountList;
    }

    public List<RebateActivityDetail> getRebateActivityDetailList() {
        return rebateActivityDetailList;
    }

    public void setRebateActivityDetailList(List<RebateActivityDetail> rebateActivityDetailList) {
        this.rebateActivityDetailList = rebateActivityDetailList;
    }

    public RebateActivityDetail getRebateActivityDetail() {
        return rebateActivityDetail;
    }

    public void setRebateActivityDetail(RebateActivityDetail rebateActivityDetail) {
        this.rebateActivityDetail = rebateActivityDetail;
    }

    public String getUsedAmount() {
        return usedAmount;
    }

    public void setUsedAmount(String usedAmount) {
        this.usedAmount = usedAmount;
    }

    public List<BigDecimal> getUsedAmountList() {
        return usedAmountList;
    }

    public void setUsedAmountList(List<BigDecimal> usedAmountList) {
        this.usedAmountList = usedAmountList;
    }

    public List<AnnualBudgetDetail> getAnnualBudgetDetailList() {
        return annualBudgetDetailList;
    }

    public void setAnnualBudgetDetailList(List<AnnualBudgetDetail> annualBudgetDetailList) {
        this.annualBudgetDetailList = annualBudgetDetailList;
    }

    public String getAnnualBudgetDetailId() {
        return annualBudgetDetailId;
    }

    public void setAnnualBudgetDetailId(String annualBudgetDetailId) {
        this.annualBudgetDetailId = annualBudgetDetailId;
    }

    public String getRebateActivityDetailId() {
        return rebateActivityDetailId;
    }

    public void setRebateActivityDetailId(String rebateActivityDetailId) {
        this.rebateActivityDetailId = rebateActivityDetailId;
    }

}


